package helper;

import jodd.io.FileNameUtil;
import org.apache.commons.lang.StringUtils;
import play.mvc.Http;

/**
 * URL相关工具类.
 */
public class UrlHelper {

    /**
     * 从地址中得到subdomain
     * @param host
     * @return
     */
    public static String getSubdomain(String host) {
        if (StringUtils.isBlank(host)) {
            return null;
        }
        String[] names = host.split("[\\.:]");
        return names[0];
    }

    public static String addParam(String key, String value) {
        String url = Http.Request.current().url;
        if (url.contains(key + "=")) {
            url = url.replaceAll(key + "=[^&]+", key + "=" + value);
        } else {
            url += (url.contains("?") ? '&' : '?') + key + "=" + value;
        }

        return url;
    }

    /**
     * 得到OSS上传图片的URL.
     */
    public static String getUploadOssImageUrl(String objectName) {
        return getUploadOssImageUrl(objectName, null);
    }

    /**
     * 得到OSS上传图片的URL, 带处理动作.
     * <p>
     * 可用action见: https://docs.aliyun.com/#/pub/oss/oss-img-api/image-processing&resize
     */
    public static String getUploadOssImageUrl(String objectName, String action) {
        String imgSrc = GlobalConfig.ALI_IMG_OSS_DOMAIN + objectName;
        if (action != null) {
            String fileExt = "." + FileNameUtil.getExtension(objectName);
            if (action.endsWith(fileExt)) {
                imgSrc += "@" + action;
            } else {
                imgSrc += "@" + action + fileExt;
            }

        }
        return imgSrc;
    }

}
